package com.nj.api.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
//该拦截器是为了判断 有关业务需要登录才能通过的拦截
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ObjectMapper objectMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        //跨域请求的预检操作，跨步会先向服务端请求是否允许跨域
        if (method.equalsIgnoreCase("options")){
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)||redisTemplate.opsForValue().get(token)==null){
            HashMap<Object, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("errMsg","请先登录");
            map.put("op","reLogin");
            String json = objectMapper.writeValueAsString(map);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(json);
            return false;
        }

        return true;
    }
}
